# -*- coding: utf-8 -*-

'''
Created on 09-08-23

@author: peterd
'''

import re

from web.service.LBCParser import LBCParser
from infra.logging import logger
from geo.models import NoSuchCity, NoSuchStreet, NoSuchLocation


class OrgListParser(LBCParser):

	def __init__(self, lbcategory, dataProcessor): 
		LBCParser.__init__(self, lbcategory, dataProcessor)
		
		self.orgs_ = {}
		self.inOrgLink_ = False


	def reset__(self):
		self.orgs_.clear()
		self.inOrgLink_ = False
		

	def parse(self, htmlPage):
		self.reset__()
		log = logger.getLogger()
		filteredContent = self.filter(htmlPage)
		log.info("Parsing html content ...")
		self.feed(self.encode(filteredContent))
		
		self.close()
		log.info("Content parsed.")
						
		return self.orgs_
		

	def start_h3(self, attrs):
		for attr, value in attrs:
			if attr == 'class' and value == 'h3zoznam':
				self.inOrgLink_ = True
				break


	def end_h3(self):
		if self.inOrgLink_:
			if self.dataProcessor_.match(self.restaurantName_):
				self.orgs_[self.restaurantName_] = self.restaurantLink_
			self.inOrgLink_ = False
			

	def start_a(self, attrs):
		if self.inOrgLink_:
			for attr, value in attrs:
				if attr == 'title':
					self.restaurantName_ = value
				if attr == 'href':
					self.restaurantLink_ = value			
					
					
	def do_handle_data(self, data):
		pass
	

	def getId(self):
		return self.__class__.__name__



class OrgParser(LBCParser):

	def __init__(self, lbcategory, name, url): 
		LBCParser.__init__(self, lbcategory, None, parsedUrl = url)
		
		self.name_ = name
		self.url_ = url
		
		self.corId_ = getCorId(self.url_)
		
		self.inAddr_ = False
		self.inContact_ = False
		

	def start_a(self, attrs):
		inHomeUrlLink = False
		url = None
		for attr, value in attrs:
			if attr == 'href':
				url = value
			if attr == 'title' and value.find(u'Domáca stránka') != -1:
				inHomeUrlLink = True
		
		if inHomeUrlLink:
			self.setHomeUrl(url)			
		
	
	def start_div(self, attrs):
		for attr, value in attrs:
			if attr == 'class' and value == 'h1help2':
				self.inContact_ = True
				break


	def start_strong(self, attrs):
		if self.inContact_:
			self.inAddr_ = True
			

	def end_strong(self):
		if self.inAddr_:
			self.inAddr_ = False
			self.inContact_ = False


	def do_handle_data(self, data):
		log = logger.getLogger()
		
		if self.inAddr_:					
			try:
				self.setCity(data)
				self.setStreet(data)
				self.createOrganization(name = self.name_, url = self.url_)
			except NoSuchCity, e:
				log.error('NoSuchCity exception caught, reason: %s' % e)
				self.cancel()				
			except NoSuchStreet, e:
				log.error('NoSuchStreet exception caught, reason: %s' % e)
				self.cancel()
			except NoSuchLocation, e:
				log.error('NoSuchLocation exception caught, reason: %s' % e)
				self.cancel()
			except Exception, e:
				log.error('Unknown exception caught, reason: %s' % e)
				self.cancel()
				
			
	def start_img(self, attrs):
		inImage = False
		src = None
		for attr, value in attrs:
			if attr == 'class' and value == 'restobrram':
				inImage = True
			if attr == 'src':
				src = value
				
		if inImage:
			self.setImage(src)
			
								
	def getId(self):
		return self.__class__.__name__
	
	
	
#
# utils
#

def getCorId(url):
	corId = None
	
	# url such as: 
	# www.obedovat.sk/bratislava/restaurant.php?id=5542&show=detaily
	# www.obedovat.sk/bratislava/photos.php?id=5542&albid=1581
	m = re.search('\.*\?id=([0-9]+)', url)
	if m:
		corId = m.group(1)
	else:
		# url such as:
		# www.obedovat.sk/bratislava/Restauracia-detaily_5542_Pizzeria_Agnezo?charset=1
		m = re.search('_([0-9]+)_', url)
		if m:
			corId = m.group(1)
	return corId


def getRelatedUrls(url):
	urls = []
	
	corId = getCorId(url)
	if corId:
		urls.append('http://www.obedovat.sk/bratislava/restaurant.menuview.php?id=%s' % corId)
		
	return urls